<template>
  <el-tooltip :disabled="disabled">
    <template #content>
      <slot name="tooltip">
        {{ content }}
      </slot>
    </template>

    <div ref="trigger" :style="triggerTooltipStyle">
      <slot>
        {{ content }}
      </slot>
    </div>
  </el-tooltip>
</template>

<script>
import {defineComponent} from 'vue';

export default defineComponent({
  name: 'ArkTooltip',
  props: {
    content: {
      type: String
    },
    line: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      disabled: true,
      resizeObserver: null,
    };
  },
  computed: {
    triggerTooltipStyle() {
      return {
        overflow: 'hidden',
        display: '-webkit-box',
        '-webkit-box-orient': 'vertical',
        '-webkit-line-clamp': this.line,
      };
    }
  },
  mounted() {
    this.triggerTooltipOverflow();
  },
  beforeUnmount() {
    const el = this.$refs.trigger;
    this.resizeObserver?.unobserve(el);
  },
  methods: {
    triggerTooltipOverflow() {
      const el = this.$refs.trigger;

      const widthOverflow = el.clientWidth < el.scrollWidth;
      const heightOverflow = el.clientHeight < el.scrollHeight;

      // 若溢出则需要提示工具
      if (widthOverflow || heightOverflow) {
        this.disabled = false;
      } else {
        this.disabled = true;
      }

      // 监听元素尺寸变化
      const thisVue = this;
      if (!this.resizeObserver) {
        this.resizeObserver = new ResizeObserver((entries) => {
          window.requestAnimationFrame(() => {
            for (const entry of entries) {
              thisVue.triggerTooltipOverflow();
            }
          });
        });
        this.resizeObserver.observe(el);
      }
    }
  }
});
</script>